import service from './axios.js';

const _get_ = function(url, params, options) {
	return new Promise((resolve, reject) => {
		service.get(url, {
				params,
				...options
			})
			.then(data => {
				resolve(data);
			})
			.catch(error => {
				reject(error);
			})
	})
}

const _post_ = function(url, data, options) {
	return new Promise((resolve, reject) => {
		service.post(url, data, options)
			.then(data => {
				resolve(data);
			})
			.catch(error => {
				reject(error);
			})
	})
}

const _upload_ = function(url, data, options) {
	const formData = new FormData();
	Object.entries(data).forEach((key, value) => {
		formData.append(key, value);
	})
	return _post_(url, formData, {
		...options,
		headers: {
			'Content-Type': 'multipart/form-data;charset=UTF-8'
		}
	});
}

const _download_ = function(url, params, options) {
	return _get_(url, params, {
		...options,
		responseType: 'blob'
	}).then(res => {
		const url = window.URL.createObjectURL(new Blob([res.data]));
		const a = document.createElement('a');
		a.download = `${params.name || document.title}-下载文件-${Date()}`;
		a.href = url;
		a.click();
		window.URL.revokeObjectURL(url);
	});
}

export {
	_get_,
	_post_,
	_upload_,
	_download_
}
